﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MESQWinform;
using MesProjectWinform.BasicData.Entity;
using Newtonsoft.Json;

namespace MesProjectWinform.BasicData.基础实现.gongwei
{
    public partial class gongup : DevExpress.XtraEditors.XtraForm
    {
        // 存储产线信息的列表
        private List<Productionline> productionlineList = new List<Productionline>();
        // 存储选中的产线ID
        private string selectedProductionlineId;
        // 当前工位ID
        private long workstationId;
        // 当前工位对象
        private Workstations currentWorkstation;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="id">工位ID</param>
        public gongup(long id)
        {
            InitializeComponent();
            this.workstationId = id;
            LoadGongXuData(); // 加载工序数据
            
            // 窗体加载时获取产线列表和工位详情
            this.Load += Gongup_Load;
            // 添加产线选择事件
            comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
        }

        /// <summary>
        /// 默认构造函数（为了兼容现有代码）
        /// </summary>
        public gongup()
        {
            InitializeComponent();
            LoadGongXuData(); // 加载工序数据
            
            // 窗体加载时获取产线列表
            this.Load += Gongup_Load;
            // 添加产线选择事件
            comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
        }
        
        /// <summary>
        /// 窗体加载事件
        /// </summary>
        private async void Gongup_Load(object sender, EventArgs e)
        {
            // 设置工位编号为只读，因为编号是自动生成的不可修改
            textEdit1.Properties.ReadOnly = true;
            
            await LoadAllProductionlines();
            
            // 如果有工位ID，加载工位详情
            if (workstationId > 0)
            {
                await LoadWorkstationDetails();
            }
        }
        
        /// <summary>
        /// 加载工位详情
        /// </summary>
        private async Task LoadWorkstationDetails()
        {
            try
            {
                // 调用API获取工位详情
                string url = $"api/WorkstationManag/GetWorkstationById?id={workstationId}";
                string response = await APIClientl.CallApiAsync(url);
                
                // 解析返回的JSON数据
                dynamic result = JsonConvert.DeserializeObject<dynamic>(response);
                
                if (result != null && result.Data != null)
                {
                    // 将动态对象转换为Workstations对象
                    currentWorkstation = JsonConvert.DeserializeObject<Workstations>(result.Data.ToString());
                    
                    // 填充表单数据
                    textEdit1.Text = currentWorkstation.Workstationcode; // 工位编号
                    textEdit2.Text = currentWorkstation.Workstationname; // 工位名称
                    memoEdit1.Text = currentWorkstation.Workstationdescription; // 工位描述
                    
                    // 设置产线下拉框选中项
                    SetSelectedProductionline(currentWorkstation.Productionid);
                    
                    // 设置工序下拉框选中项
                    SetSelectedProcess(currentWorkstation.Processid);
                }
                else
                {
                    XtraMessageBox.Show("未找到工位信息或数据格式错误", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载工位详情失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 设置产线下拉框选中项
        /// </summary>
        private void SetSelectedProductionline(string productionlineId)
        {
            // 根据产线ID查找对应的索引
            for (int i = 0; i < productionlineList.Count; i++)
            {
                if (productionlineList[i].Id.ToString() == productionlineId)
                {
                    comboBox1.SelectedIndex = i;
                    break;
                }
            }
        }
        
        /// <summary>
        /// 设置工序下拉框选中项
        /// </summary>
        private void SetSelectedProcess(string processId)
        {
            // 遍历工序下拉框查找匹配项
            for (int i = 0; i < comboBox2.Items.Count; i++)
            {
                if (comboBox2.Items[i].ToString() == processId)
                {
                    comboBox2.SelectedIndex = i;
                    break;
                }
            }
        }

        /// <summary>
        /// 加载工序数据
        /// </summary>
        private void LoadGongXuData()
        {
            // 清空已有项
            comboBox2.Items.Clear();
            
            // 添加工序选项
            comboBox2.Items.Add("拼版投入");
            comboBox2.Items.Add("点胶");
            comboBox2.Items.Add("AOI");
            comboBox2.Items.Add("SPI");
            comboBox2.Items.Add("烘烤");
            comboBox2.Items.Add("22");
            comboBox2.Items.Add("后盖01");
            comboBox2.Items.Add("后盖02");
            
            // 默认选择第一项
            if (comboBox2.Items.Count > 0)
            {
                comboBox2.SelectedIndex = 0;
            }
        }
        
        /// <summary>
        /// 加载所有产线数据
        /// </summary>
        private async Task LoadAllProductionlines()
        {
            try
            {
                // 调用API获取所有产线数据
                string response = await APIClientl.CallApiAsync("api/Productionline/GetAllProductionline", "GET");
                
                // 解析返回的JSON数据
                ProductionlineDto productionlineDto = JsonConvert.DeserializeObject<ProductionlineDto>(response);
                
                // 由于ProductionlineDto已设置默认值，无需检查是否为null
                // 保存产线列表以便后续使用
                productionlineList = productionlineDto.Data;
                
                // 清空下拉框
                comboBox1.Items.Clear();
                
                // 将产线名称添加到下拉框
                foreach (var productionline in productionlineList)
                {
                    comboBox1.Items.Add(productionline.Productionlinename);
                }
                
                // 如果有数据，默认选择第一项
                if (comboBox1.Items.Count > 0)
                {
                    comboBox1.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取产线数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button2_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取表单数据
                string workstationName = textEdit2.Text.Trim(); // 工位名称
                string workstationCode = textEdit1.Text.Trim(); // 工位编号
                string description = memoEdit1.Text.Trim(); // 工位描述
                
                // 检查必填字段
                if (string.IsNullOrEmpty(workstationCode))
                {
                    XtraMessageBox.Show("请填写工位编号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                
                if (string.IsNullOrEmpty(selectedProductionlineId))
                {
                    XtraMessageBox.Show("请选择产线", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                
                // 获取选中的工序
                string processId = comboBox2.SelectedItem?.ToString() ?? "";
                if (string.IsNullOrEmpty(processId))
                {
                    XtraMessageBox.Show("请选择工序", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                
                // 获取选中的产线名称
                string productionLineName = comboBox1.SelectedItem?.ToString() ?? "";
                
                // 创建工位对象
                Workstations workstation = new Workstations
                {
                    Id = workstationId, // 保持原ID
                    Workstationname = workstationName,
                    Workstationcode = workstationCode,
                    Productionid = selectedProductionlineId,
                    Productionlinename = productionLineName,
                    Processid = processId,
                    Workstationdescription = description,
                    Workstationattributes = currentWorkstation?.Workstationattributes ?? " ", // 保持原属性
                    Workstationuserid = currentWorkstation?.Workstationuserid ?? " ", // 保持原用户
                    IsDeleted = false,
                    CreatedBy = currentWorkstation?.CreatedBy ?? "admin",
                    CreatedTime = currentWorkstation?.CreatedTime ?? DateTime.Now,  // 保留原始创建时间
                    UpdatedBy = "张三",
                    UpdatedTime = DateTime.Now
                };
                
                // 将对象序列化为JSON
                string jsonData = JsonConvert.SerializeObject(workstation);
                
                // 调用API更新工位
                string url = "api/WorkstationManag/UpdateWorkstation";
                string response = await APIClientl.CallApiAsync(url, "POST", jsonData);
                
                // 解析返回结果
                dynamic result = JsonConvert.DeserializeObject(response);
                
                // 显示成功消息
                XtraMessageBox.Show("修改工位成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                
                // 关闭窗口
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"修改工位时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button1_Click(object sender, EventArgs e)
        {
            // 如果有工位ID，重新加载工位详情
            if (workstationId > 0)
            {
                await LoadWorkstationDetails();
            }
            else
            {
                // 清空所有输入框
                textEdit2.Text = string.Empty; // 工位名称
                textEdit1.Text = string.Empty; // 工位编号
                memoEdit1.Text = string.Empty; // 工位描述
                
                // 重置下拉框选择（如果需要的话）
                if (comboBox1.Items.Count > 0)
                {
                    comboBox1.SelectedIndex = 0;
                }
                
                if (comboBox2.Items.Count > 0)
                {
                    comboBox2.SelectedIndex = 0;
                }
            }
        }
        
        /// <summary>
        /// 产线动态获取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex >= 0 && comboBox1.SelectedIndex < productionlineList.Count)
            {
                // 获取选中的产线对象
                Productionline selectedProductionline = productionlineList[comboBox1.SelectedIndex];
                // 保存选中产线的ID
                selectedProductionlineId = selectedProductionline.Id.ToString();
            }
        }
        
        /// <summary>
        /// 工序死值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 获取选中的工序
            string selectedGongXu = comboBox2.SelectedItem?.ToString();
        }
    }
}